﻿using AutoMapper;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Linq;
using YaAppoint.Appointments.Pools;
using YaAppoint.Response;

namespace YaAppoint.Appointments.ScheduleOverrides
{
    /// <summary>
    /// 特殊排班服务
    /// </summary>
    [RemoteService(isEnabled: false)]
    public class ScheduleOverrideAppService(IRepository<ScheduleOverride,Guid> scheduleOverrideRepository,
                                            IRepository<Device,Guid> deviceRepostory,
                                            IRepository<Pool,Guid> poolRepository,
                                            IMapper mapper,
                                            AsyncQueryableExecuter queryableExecuter,
                                            IConfiguration configuration,
                                            ScheduleOverrideManager scheduleOverrideManager,
                                            IRepository<Department,Guid> departmentRepository):ApplicationService,IScheduleOverrideAppService,ITransientDependency
    {
        private readonly IRepository<ScheduleOverride, Guid> _scheduleOverrideRepository = scheduleOverrideRepository;
        private readonly IMapper _mapper = mapper;
        private readonly AsyncQueryableExecuter _queryableExecuter = queryableExecuter;
        private readonly IRepository<Department, Guid> _departmentRepository = departmentRepository;
        private readonly IConfiguration _configration = configuration;
        private readonly ScheduleOverrideManager _manager = scheduleOverrideManager;
        private readonly IRepository<Device, Guid> _deviceRepostory = deviceRepostory;
        private readonly IRepository<Pool, Guid> _poolRepository = poolRepository;

        /// <summary>
        /// 左侧导航栏树形数据
        /// </summary>
        /// <param name="depId">登录科室Id</param>
        /// <returns></returns>
        public async Task<BackJson> GetTreeData(Guid? depId)
        {
            var query = await _departmentRepository.GetQueryableAsync();
            if (depId != null)
            {
                query = query.Where(x=>x.Id==depId);

            }

            var list = await _queryableExecuter.ToListAsync(query);
            var data = new
            {
                name = _configration["InstitutionName"],
                id = 1,
                icon = "fa fa-hospital",
                children = list.Select(x => new // 科室
                {
                    name = x.Name,
                    id = x.Id,
                    icon = "fa fa-building",
                    children = x.Devices!.OrderBy(x=>x.DeviceTypeId).Select(device => new
                    {
                        name =device.Name,
                        id = device.Id,
                        icon = "fa fa-list"
                    }),
                })
            };

            var res = new List<object>();
            res.Add(data);

            return new BackJson()
            {
                code = 0,
                data= res
            };
        }


        /// <summary>
        /// 获取特定设备特殊排班列表
        /// </summary>
        public async Task<BackJson> GetList(Guid deviceid)
        {
            var query = await _scheduleOverrideRepository.GetQueryableAsync();
            query = query.Where(x => x.DeviceId == deviceid).OrderBy(x => x.Date);
            var list = await _queryableExecuter.ToListAsync(query);
            return new BackJson()
            {
                code = 0,
                data = _mapper.Map<List<ScheduleOverride>,List<ScheduleOverrideDto>>(list)
            };
        }

        /// <summary>
        /// 提交新建
        /// </summary>
        public async Task<BackJson> SubmitCreat(CreateScheduleOverrideDto dto)
        {
            var old = await _scheduleOverrideRepository.FirstOrDefaultAsync(x => x.DeviceId == dto.DeviceId && x.Date == dto.Date); ;
            if (old != null)
            { 
                await _scheduleOverrideRepository.DeleteAsync(old);
            }

            var scheduleOverride = _mapper.Map<CreateScheduleOverrideDto, ScheduleOverride>(dto);
            scheduleOverride.Device = await _deviceRepostory.GetAsync(dto.DeviceId);
            await _scheduleOverrideRepository.InsertAsync(scheduleOverride);
            return new BackJson()
            {
                code = 0,
                msg = "保存成功"
            };
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        public async Task<BackJson> GetAsync(Guid id)
        {
            return new BackJson();
        }

        /// <summary>
        /// 判断给定设备给定日期下是否已存在特殊排班安排
        /// </summary>
        public async Task<BackJson> IsAlreadyExist(Guid deviceId, DateTime date)
        {
            var scheduleOverride = await _scheduleOverrideRepository.FirstOrDefaultAsync(x => x.DeviceId == deviceId && x.Date.Date == date.Date);

           

            var res = new BackJson();
            res.code = 0;
            if (scheduleOverride != null)
            {
                var pools = await _poolRepository.GetListAsync(x => x.ScheduleOverrideId == scheduleOverride.Id);
                if (pools.Count > 0)
                {
                    foreach (var pool in pools)
                    { 
                        if (pool.Appointments.Count>0)
                        {
                            throw new BusinessException(CustomErrorCodes.AppointmentExistInSchduleOverride);
                        }
                    }
                }
                res.data = new
                {
                    exist = true
                };
            }
            else
            {
                res.data = new
                {
                    exist = false
                };
            }

            return res;
        }


        public async Task<BackJson> Delete(Guid id)
        {
            var scheduleOverride = await _scheduleOverrideRepository.FirstOrDefaultAsync(x=>x.Id==id);
            if (scheduleOverride == null)
            {
                throw new BusinessException(CustomErrorCodes.ScheduleOverrideNotExist);
            }
            await _manager.Delete(scheduleOverride);

            return new BackJson()
            {
                code = 0,
                msg = "删除成功"
            };
        }

    }
}
